package cn.wen233.spring.discovery;

import cn.wen233.client.config.SunglowServerProperties;
import cn.wen233.client.service.ClientCoreService;
import cn.wen233.spring.config.SunglowProperties;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * DiscoveryClient
 *
 * @author wenei
 * @date 2021-10-26 19:43
 */
public class SunglowDiscoveryClient implements DiscoveryClient {

    private final ClientCoreService clientCoreService = ClientCoreService.getInstance();

    private SunglowProperties sunglowProperties;

    private Map<String, List<ServiceInstance>> serviceAndInstanceMap = new ConcurrentHashMap<>();

    public SunglowDiscoveryClient(SunglowProperties properties) {
        SunglowServerProperties.setIp(properties.getIp());
        SunglowServerProperties.setPort(properties.getPort());
        SunglowServerProperties.setNamespaceId(properties.getNamespaceId());
        this.sunglowProperties = properties;
    }

    @Override
    public String description() {
        return "Sunglow spring cloud discovery client";
    }

    @Override
    public List<ServiceInstance> getInstances(String serviceId) {
        if (serviceAndInstanceMap.containsKey(serviceId)) {
            return serviceAndInstanceMap.get(serviceId);
        }
        List<ServiceInstance> serviceInstances = clientCoreService.getAllInstance(sunglowProperties.getNamespaceId(), serviceId)
                .stream()
                .map(SunglowServiceInstance::new)
                .collect(Collectors.toList());
        serviceAndInstanceMap.put(serviceId, serviceInstances);
        return serviceInstances;
    }

    @Override
    public List<String> getServices() {
        return new ArrayList<>(serviceAndInstanceMap.keySet());
    }
}
